package at.tasat.util;

public class IntKeyMap<T> {
	private final int min;
	private final int max;
	private final Object[] values;
	private int size;

	public IntKeyMap(int min, int max) {
		this.min = min;
		this.max = max;
		values = new Object[max - min + 1];
		size = 0;
	}

	public void put(int key, T value) {
		assert inRange(key);
		assert value != null;
		int index = keyToIndex(key);
		assert values[index] == null;
		values[index] = value;
		size++;
	}

	public boolean containsKey(int key) {
		assert inRange(key);
		return values[keyToIndex(key)] != null;
	}

	public void clear() {
		for (int i = 0; i < values.length; i++) {
			values[i] = null;
		}
		size = 0;
	}

	public T get(int key) {
		assert inRange(key);
		int index = keyToIndex(key);
		@SuppressWarnings("unchecked")
		T value = (T) values[index];
		if (value == null) {
			throw new IllegalArgumentException("Map does not contain this key");
		}
		return value;
	}

	public int size() {
		return size;
	}

	public void remove(int key) {
		assert inRange(key);
		int index = keyToIndex(key);
		if (values[index] != null) {
			values[index] = null;
			size--;
		} else {
			throw new IllegalArgumentException("Map does not contain this key");
		}
	}
	
	public int getMinimalValue() {
		return min;
	}
	
	public int getMaximalValue() {
		return max;
	}

	private boolean inRange(int value) {
		return value >= min && value <= max;
	}

	private int keyToIndex(int value) {
		return value - min;
	}
}
